<?php
namespace control;

// 模具保养维修
class moldMaintenanceClass extends adIndexClass
{
	private const page  = 'moldMaintenance';
	private const table = 'mold_maintenance';
	private const title = '模具保养维修';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => "模具编码",
                        'width' => 200,
                    ],
                    'name'  => [
                        'name'  => '模具名称',
                        'width' => 200,
                    ],
                    'model'         => [
                        'name'  => '规格',
                        'width' => 200,
                    ],
                    'body'          => [
                        'name'  => '保养维修内容',
                        'width' => 200,
                    ],
                    'fee'          => [
                        'name'  => "费用(".static::$unit.")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'operator'          => [
                        'name'  => '操作人',
                        'width' => 150,
                    ],
                    'time'          => [
                        'name'  => '日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,

                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "模具编码"   => text(array("name" => "code")),
                    "模具名称"   => text(array("name" => "name")),
                    "保养维修内容"   => text(array("name" => "body")),
                ],
                [
                    "操作人"   => text(array("name" => "operator")),
                    "日期" => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    "备注"   => text(array("name" => "text")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$where = '';
		$equal = [
			'coid' => self::$coid,
		];
		$like  = [
			'operator' => $this->post('operator'),
			'text'     => $this->post('text'),
		];
		//生成查询语句
		$targetWhere = search([
			"like" => [
				'code' => $this->post('code'),
				'name' => $this->post('name'),
			],
		]);
		if ($targetWhere) {
			$where .= " and mdid IN (SELECT id FROM `mold` WHERE 1=1 $targetWhere) ";
		}
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'time', 'orderDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				"edit"   => ["title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"],
			);
			$target   = query('mold', " id ='$array[mdid]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                    case 'model':
                        $row[] = $target[$key];
                        break;
                    case 'operator':
                        $row[] = self::findStaff($array['operator']);
                        break;
                    case 'time':
                        $row[] = self::formatDate($array['time']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(fee),0) as fee",
        ]);
        $total    = [
            'fee'        => self::formattingFigure($totalQuery['fee']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id       = $this->post('id');
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . '模具' => hidden(['name' => 'mdid', 'value' => $info['mdid']])
                        . '<span id="moldName" style="max-width: 80%;" class="exceed-ellipsis">' . ($info['mdid'] ? query('mold', "id = '$info[mdid]'", 'name')['name'] : '未选择') . '</span>'
                        . "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addTarget',{})\" style='margin-left: 10px'>选择</span>",
                    '操作人' => selectMultiple(["name" => "operator", 'title' => '操作人', 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['operator']]),
                ],
                [
                    '费用' => text(['name' => "fee", 'type' => 'number', 'unit'=>static::$unit,'value' => $info['fee']]),
                    '日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->time, 'laydate' => ['type' => 'datetime'],]),
                ],
                [
                    must . '保养维修内容' => textarea(['name' => "body", 'class' => 'text', 'value' => $info['body']]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],

            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $html .= <<<EOT
		<script>
		//选择明细
        function addTarget(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addTargetEdit', $("form[name='mxForm']").serialize(),function(resp) {
	         if (resp.warn === 2){
	            $("[name='mdid']").val(resp.res.mdid);
	            $("#moldName").html(resp.res.name);
	         }else{
	             msg(resp.warn);
	         }
	        },'json');
        }
        
		</script>
EOT;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

	/**
	 *选择生产模具
	 *
	 * @return bool|string
	 */
	public function addTarget(): bool|string
	{
		$html   =
			select(["name" => "type", "title" => "分类", "option" => explode('，', para('moldType'))]) .
			text(["name" => "code", "title" => "模具编码"]) .
			text(["name" => "moldName", "title" => "模具名称"]) .
			text(["name" => "model", "title" => "规格型号"]);
		$button = "<input style='margin-left: 5px' onclick=\"addTarget();$('#" . self::page . "AddTarget').hide()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
	}

	/**
	 *添加模具
	 */
	public function addTargetSearch(): bool|string
	{
		$like  = [
			'name'  => $this->post('moldName'),
			'code'  => $this->post('code'),
			'model' => $this->post('model'),
		];
		$equal = [
			'type'  => $this->post('type'),
			'state' => '启用',
			'coid'  => self::$coid,
		];
		$where = search(["like" => $like, "=" => $equal]);
		$page  = $this->page([
			"table" => 'mold',
			"field" => "*",
			"where" => $where,
			"order" => "time ASC",
		]);
		//获取表头
		$tr[] = ['', '分类', '模具编码', '模具名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$tr[] = array(
				"<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
				$array['type'],
				$array['code'],
				$array['name'],
				$array['model'],
			);
		}
		$json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addTargetEdit(): bool|string
	{
		$mdid = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mdid)) {
			$json['warn'] = '请选择模具';
		} else {
			$mold = query('mold', "id = '$mdid' ");
			$json = [
				'warn' => 2,
				'res'  => [
					'name' => $mold['code'] . '-' . $mold['name'] . '-' . $mold['model'],
					'mdid' => $mold['id'],
				],
			];
		}
		return json_encode($json, 320);
	}


	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'mdid'       => $this->post('mdid'),
			'body'       => $this->post('body'),
            'fee'       => $this->post('fee'),
			'operator'   => $this->post('operator'),
			'commitTime' => $this->post('commitTime'),
			'text'       => $this->post('text'),
			'orderDate'  => $this->post('orderDate'),
		];
		$annotation = [
			'mdid' => '模具id',
			'body' => '保养维修内容',
		];
		$rules      = [
			'mdid' => 'required',
			'body' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'YRSQ' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $orderNo,
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}

			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$mold = query('mold', " id = '$info[mdid]' ");
			//菜单
			$data = array(
				"id" => $info['id'],
			);
			//按钮
			$button[] = [
				"name"  => "编辑",
                "type" => "弹出层",
                "cla" => $this->get('cla'),
                "fun" => "edit",
                "post" => ["id" => $info['id']],
				'style' => 'li-btn-blue-bg',
			];
			//按钮
			$button[] = [
				"name" => "删除",
				"type" => "弹出层",
				"cla"  => $this->get('cla'),
				"fun"  => "operate",
				"post" => ["act" => 'del', "id" => $info['id']],
			];
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"模具" => $mold['code'] . ' - ' . $mold['name'] . ' - ' . $mold['model'],
                        "操作人" => $info['operator'],
                        "费用(".static::$unit.")" => $info['fee'],
                        "日期"  => $info['orderDate'],
					],
					[
						"保养内容" => pre($info['body']),
					],
					[
						"备注" => pre($info['text']),
					],
				],
				'系统信息'   => [
					[
						"单据编号" => $info['orderNo'],
						"创建人"  => self::findStaff($info['stid']),
						"创建时间" => $info['time'],
					],
				],
			]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act = $this->post('act') ?? '';
		// 需要密码
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => false,
				'word'     => false,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已审核') {
					$warn = "删除失败：已审核，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
}
